package com.ncst.backend.controller;

import com.ncst.backend.common.Result;
import com.ncst.backend.domain.InspectionRequest;
import com.ncst.backend.domain.MedicalTechnology;
import com.ncst.backend.domain.Register;
import com.ncst.backend.service.InspectionRequestService;
import com.ncst.backend.service.MedicalTechnologyService;
import com.ncst.backend.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 患者消费记录控制器
 */
@RestController
@RequestMapping("/fee/log")
public class FeeLogController {
    
    @Autowired
    private RegisterService registerService;
    
    @Autowired
    private InspectionRequestService inspectionRequestService;
    
    @Autowired
    private MedicalTechnologyService medicalTechnologyService;
    
    /**
     * 分页查询患者消费记录列表
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> getFeeLogList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String caseNumber,
            @RequestParam(required = false) String realName) {
        
        try {
            Map<String, Object> result = new HashMap<>();
            List<Map<String, Object>> dataList = new ArrayList<>();
            
            // 根据病历号或姓名查询register
            List<Register> registerList = new ArrayList<>();
            if (caseNumber != null || realName != null) {
                Register register = new Register();
                register.setCaseNumber(caseNumber);
                register.setRealName(realName);
                registerList = registerService.getByCondition(register);
            } else {
                // 如果没有查询参数，返回空列表
                result.put("list", new ArrayList<>());
                result.put("total", 0);
                result.put("pageNum", pageNum);
                result.put("pageSize", pageSize);
                result.put("pages", 0);
                return Result.success(result);
            }
            
            // 根据registerId查询inspection_request
            List<InspectionRequest> inspectionRequests = new ArrayList<>();
            if (!registerList.isEmpty()) {
                List<Integer> registerIds = registerList.stream().map(Register::getId).collect(Collectors.toList());
                for (Integer registerId : registerIds) {
                    List<InspectionRequest> requests = inspectionRequestService.getByRegisterId(registerId);
                    inspectionRequests.addAll(requests);
                }
            }
            
            // 构建返回数据
            for (InspectionRequest request : inspectionRequests) {
                Map<String, Object> dataMap = new HashMap<>();
                
                // 获取患者信息
                Register register = registerService.getById(request.getRegisterId());
                if (register != null) {
                    dataMap.put("caseNumber", register.getCaseNumber());
                    dataMap.put("realName", register.getRealName());
                    dataMap.put("registMethod", register.getRegistMethod() != null ? register.getRegistMethod() : "");
                }
                
                // 获取项目信息
                MedicalTechnology tech = medicalTechnologyService.getById(request.getMedicalTechnologyId());
                if (tech != null) {
                    dataMap.put("techName", tech.getTechName());
                    dataMap.put("techPrice", tech.getTechPrice());
                } else {
                    dataMap.put("techName", "未知项目");
                    dataMap.put("techPrice", new BigDecimal(0));
                }
                
                // 设置其他信息
                dataMap.put("quantity", 1); // 假设数量默认为1
                dataMap.put("inspectionState", request.getInspectionState() != null ? request.getInspectionState() : "");
                dataMap.put("creationTime", request.getCreationTime());
                
                dataList.add(dataMap);
            }
            
            // 分页处理
            int total = dataList.size();
            int start = (pageNum - 1) * pageSize;
            int end = Math.min(start + pageSize, total);
            List<Map<String, Object>> pageList = start < total ? dataList.subList(start, end) : new ArrayList<>();
            
            result.put("list", pageList);
            result.put("total", total);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("pages", (total + pageSize - 1) / pageSize);
            
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取患者消费记录失败: " + e.getMessage());
        }
    }
}